package com.ren.mianshi;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gyf.immersionbar.ImmersionBar;
import com.ren.mianshi.db.RoomManager;
import com.ren.mianshi.db.dao.ChatDao;
import com.ren.mianshi.db.table.ChatTable;
import com.ren.mianshi.http2.HttpManager;
import com.ren.mianshi.http2.callback.CommonCallback;
import com.ren.mianshi.http2.entity.CommonResponse;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

public class ChatActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private EditText et_send;


    private ChatAdapter mAdapter;
    private List<ChatTable> mList = new ArrayList<>();
    private ChatDao mChatDao;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initStatusBar();
        setContentView(R.layout.activity_chat);
        mRecyclerView = findViewById(R.id.recyclerView);
        et_send = findViewById(R.id.et_send);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        manager.setReverseLayout(true);
        mRecyclerView.setLayoutManager(manager);
        mAdapter = new ChatAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mChatDao = RoomManager.getInstance().getAppDatabase().chatDao();
        updateChatMessages();

        findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        findViewById(R.id.iv_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendMessage();
                et_send.setText("");
                updateChatMessages();
            }
        });
    }


    private void sendMessage() {
        String q = et_send.getEditableText().toString();
        if (TextUtils.isEmpty(q)) {
            return;
        }
        ChatTable sendTable = new ChatTable();
        sendTable.messageType = VIEW_TYPE_TEXT_RIGHT;
        sendTable.answer = q;
        sendTable.timeillons = System.currentTimeMillis();
        mChatDao.insert(sendTable);
        requestSendMessage(q);
    }

    private void requestSendMessage(String msg) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        Call<CommonResponse<ChatTable>> call = HttpManager.getInstance().getAppApiService().getChatMessage(msg);
        call.enqueue(new CommonCallback<CommonResponse<ChatTable>>() {
            @Override
            public void onSuccess(Call<CommonResponse<ChatTable>> call, CommonResponse<ChatTable> chatTableCommonResponse) {
                ChatTable table = chatTableCommonResponse.data;
                if (table != null) {
                    table.messageType = VIEW_TYPE_TEXT_LEFT;
                    table.timeillons = System.currentTimeMillis();
                    mChatDao.insert(table);
                }
                updateChatMessages();
            }
        });
    }


    private void initStatusBar() {
        ImmersionBar.with(this)
                .statusBarDarkFont(false)
                .init();
    }

    private void updateChatMessages() {
        mList = mChatDao.queryListAllDesc();
        mAdapter.notifyDataSetChanged();
    }

    private void testData() {
        for (int i = 0; i < 15; i++) {
            ChatTable chatTable = new ChatTable();
            chatTable.timeillons = System.currentTimeMillis();
            if (i % 2 == 0) {
                chatTable.messageType = VIEW_TYPE_TEXT_LEFT;
                chatTable.answer = "你好你好";
            } else {
                chatTable.messageType = VIEW_TYPE_TEXT_RIGHT;
                chatTable.answer = "hello hello";
            }
            mChatDao.insert(chatTable);
        }

    }


    public static final int VIEW_TYPE_TEXT_LEFT = 0;
    public static final int VIEW_TYPE_TEXT_RIGHT = 1;
    public static final int VIEW_TYPE_TIME = 2;

    private class ChatAdapter extends RecyclerView.Adapter<ChatViewHolder> {

        @NonNull
        @Override
        public ChatViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            int res;
            if (viewType == VIEW_TYPE_TEXT_LEFT) {
                res = R.layout.item_chat_left;
            } else if (viewType == VIEW_TYPE_TEXT_RIGHT) {
                res = R.layout.item_chat_right;
            } else {
                res = VIEW_TYPE_TIME;
            }
            View inflate = View.inflate(ChatActivity.this, res, null);
            return new ChatViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull ChatViewHolder holder, int position) {
            ChatTable chatTable = mList.get(position);
            if (chatTable.messageType == VIEW_TYPE_TEXT_LEFT) {
                holder.tv_left_chatContent.setText(chatTable.answer);
            } else if (chatTable.messageType == VIEW_TYPE_TEXT_RIGHT) {
                holder.tv_right_chatContent.setText(chatTable.answer);
            }

        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

        @Override
        public int getItemViewType(int position) {
            ChatTable chatTable = mList.get(position);
            return chatTable.messageType;
        }
    }


    public static class ChatViewHolder extends RecyclerView.ViewHolder {
        public ImageView ivHead, iv_copy, iv_voice, iv_refresh, iv_more;
        public TextView tv_left_chatContent, tv_right_chatContent;


        public ChatViewHolder(@NonNull View itemView) {
            super(itemView);
            ivHead = itemView.findViewById(R.id.iv_head);
            iv_copy = itemView.findViewById(R.id.iv_copy);
            iv_voice = itemView.findViewById(R.id.iv_voice);
            iv_refresh = itemView.findViewById(R.id.iv_refresh);
            iv_more = itemView.findViewById(R.id.iv_more);
            tv_left_chatContent = (TextView) itemView.findViewById(R.id.tv_left_chatContent);
            tv_right_chatContent = (TextView) itemView.findViewById(R.id.tv_right_chatContent);
            tv_right_chatContent = (TextView) itemView.findViewById(R.id.tv_right_chatContent);
        }

    }


}
